<template>
  <div class="schedule-container">
    <!-- 筛选区域 -->
    <div class="filter-section">
      <div class="filter-item">
        <span>开始日期</span>
        <el-date-picker
            v-model="startTime"
            type="date"
            placeholder="选择开始日期"
            value-format="YYYY-MM-DD"
            style="width: 160px"
        />
      </div>
      <div class="filter-item">
        <span>结束日期</span>
        <el-date-picker
            v-model="endTime"
            type="date"
            placeholder="选择结束日期"
            value-format="YYYY-MM-DD"
            style="width: 160px"
        />
      </div>
      <div class="filter-item">
        <span>门店</span>
        <el-select
            v-model="selectedStore"
            placeholder="请选择门店"
            style="width: 200px"
        >
          <el-option
              v-for="store in stores"
              :key="store.value"
              :label="store.label"
              :value="store.value"
          />
        </el-select>
      </div>
      <div class="filter-item">
        <el-button type="primary" @click="handleSearch">查询</el-button>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="action-section">
      <el-button type="warning" @click="handleExport">导出</el-button>
      <el-button type="info" @click="showManualDialog">手动排班</el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <el-table
          :data="tableData"
          border
          style="width: 100%"
      >
        <el-table-column prop="id" label="工号" width="80" />
        <el-table-column prop="name" label="姓名" width="100" />
        <el-table-column prop="storeName" label="所属门店" width="150" />
        <el-table-column prop="role" label="职位" width="100" />
        <el-table-column prop="shift_09_09" label="周四(09.09)" width="100" />
        <el-table-column prop="shift_09_10" label="周五(09.10)" width="100" />
        <el-table-column prop="shift_09_11" label="周六(09.11)" width="100" />
        <el-table-column prop="shift_09_12" label="周日(09.12)" width="100" />
        <el-table-column prop="shift_09_13" label="周一(09.13)" width="100" />
        <el-table-column prop="shift_09_14" label="周二(09.14)" width="100" />
        <el-table-column prop="shift_09_15" label="周三(09.15)" width="100" />
        <el-table-column prop="shift_09_16" label="周四(09.16)" width="100" />
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="totalData"
          layout="total, prev, pager, next, jumper"
          @current-change="handlePageChange"
      />
    </div>
  </div>
  <el-dialog
      v-model="manualDialogVisible"
      title="手动排班"
      width="600px"
      @closed="handleDialogClose"
  >
    <el-form
        ref="manualFormRef"
        :model="manualForm"
        label-width="100px"
        :rules="formRules"
    >
      <el-form-item label="选择员工" prop="employeeId">
        <el-select
            v-model="manualForm.employeeId"
            placeholder="请选择员工"
            filterable
            remote
            :remote-method="loadEmployees"
            :loading="employeeLoading"
            style="width: 100%"
        >
          <el-option
              v-for="item in employeeOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          >
            <!-- 简化显示，移除门店信息 -->
            <span>{{ item.name }}</span>
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="排班日期" prop="date">
        <el-date-picker
            v-model="manualForm.date"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="班次类型" prop="shiftType">
        <el-select
            v-model="manualForm.shift"
            placeholder="请选择班次"
            style="width: 100%"
        >
          <el-option label="早班" value="早班" />
          <el-option label="晚班" value="晚班" />
          <el-option label="休" value="休" />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
        <span class="dialog-footer">
          <el-button @click="manualDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitManualSchedule">确认</el-button>
        </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {ref, onMounted, reactive} from 'vue';
import axios from 'axios';
import {ElMessage} from "element-plus";

// 数据相关变量
const tableData = ref([]);
const stores = ref([]);
const selectedStore = ref('');
const dateRange = ref(null);
const currentPage = ref(1);
const pageSize = ref(30);
const totalData = ref(0);

const manualDialogVisible = ref(false)
const employeeLoading = ref(false)
const employeeOptions = ref([])
const startTime = ref(null);
const endTime = ref(null);
const manualForm = ref({
  employeeId: '',
  date: '',
  shift: ''
})

const formRules = {
  employeeId: [{ required: true, message: '请选择员工', trigger: 'change' }],
  date: [{ required: true, message: '请选择日期', trigger: 'change' }]
}

// 显示弹窗
const showManualDialog = () => {
  manualDialogVisible.value = true
}

// 加载员工数据
const loadEmployees = () => {
  axios.get("/employ/getAllName").then(res => {
    // 修改点：使用 res.data.obj 获取实际数据数组
    employeeOptions.value = res.data.obj.map(item => ({
      id: item.id,
      name: item.name,
      // 注意：根据你的接口返回数据，这里没有storeName字段
      // 如果确实需要显示门店信息，需要确保接口返回该字段
      storeName: item.storeName || '未知门店' // 添加默认值或移除该字段
    }))
  })
}
// 转换排班数据格式 - 按姓名合并数据
const transformScheduleData = (data) => {
  const groupedData = {};

  data.forEach(item => {
    // 仅使用姓名作为分组键
    const groupKey = item.name;

    if (!groupedData[groupKey]) {
      groupedData[groupKey] = {
        id: item.id, // 保留第一个出现的工号
        name: item.name,
        storeName: item.store,
        role: item.role,
        shift_09_09: '',
        shift_09_10: '',
        shift_09_11: '',
        shift_09_12: '',
        shift_09_13: '',
        shift_09_14: '',
        shift_09_15: '',
        shift_09_16: ''
      };
    }

    const date = new Date(item.date);
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const dateKey = `shift_${month}_${day}`;

    if (groupedData[groupKey][dateKey] !== undefined) {
      // 如果该日期已有班次，用逗号分隔多个班次
      if (groupedData[groupKey][dateKey]) {
        groupedData[groupKey][dateKey] += `, ${item.shift}`;
      } else {
        groupedData[groupKey][dateKey] = item.shift;
      }
    }
  });

  return Object.values(groupedData);
};

// 格式化日期
const formatDate = (date) => {
  const d = new Date(date);
  const year = d.getFullYear();
  const month = (d.getMonth() + 1).toString().padStart(2, '0');
  const day = d.getDate().toString().padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// 获取排班数据
const getScheduleData = async () => {
  try {
    // 构建请求参数
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    };

    if (selectedStore.value) {
      params.storeId = selectedStore.value;
    }

    if (dateRange.value && dateRange.value.length === 2) {
      params.startDate = formatDate(dateRange.value[0]);
      params.endDate = formatDate(dateRange.value[1]);
    }

    const response = await axios.get(`/schedule/getSchedules/${currentPage.value}/${pageSize.value}`, {params});
    if (response.data.code === 200) {
      // 假设后端返回的分页数据在response.data.obj中
      const pageData = response.data.obj;
      tableData.value = transformScheduleData(pageData.records);
      totalData.value = pageData.total;
    } else {
      console.error('获取排班数据失败:', response.data.msg);
    }
  } catch (error) {
    console.error('请求排班数据出错:', error);
  }
};
// 弹窗的确认窗口
const submitManualSchedule = () => {
  axios.post(`/schedule/addSchedule`,manualForm.value).then(res => {
    ElMessage.success('添加成功');
    manualDialogVisible.value = false;
    getScheduleData();
  })
};
// 导出数据
const handleExport = () => {
  axios.get('/schedule/export', {
    responseType: 'blob', // 关键参数声明二进制流
    params: { // 传递筛选参数（与查询逻辑一致）

    }
  }).then(res => {
    // 创建Blob链接并触发下载
    const blob = new Blob([res.data], { type: res.headers['content-type'] });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');

    // 从响应头获取文件名（需后端配合）
    const fileName = decodeURIComponent(
        res.headers['content-disposition'].split('filename*=UTF-8\'\'')[1] ||
        '登录日志.xlsx'
    );

    link.href = url;
    link.download = fileName;
    link.style.display = 'none';
    document.body.appendChild(link);
    link.click();

    // 清理资源
    window.URL.revokeObjectURL(url);
    document.body.removeChild(link);
    ElMessage.success('导出成功');
  }).catch(err => {
    ElMessage.error('导出失败：' + (err.response?.data?.message || '未知错误'));
  });
};
// 获取门店数据
const getStores = () => {
  axios.get(`/store/getStoreName`).then(res => {
    // 将返回的数组对象转换为element需要的格式
    stores.value = res.data.map(item => ({
      value: item.id,
      label: item.name
    }));
  });
};

// 查询方法
const handleSearch = async () => {
  try {
    // 构建请求参数对象（对应ScheduleDTO）
    const scheduleDTO = {
      startTime: startTime.value,  // 确保和日期选择器绑定的变量名一致
      endTime: endTime.value,
      storeId: selectedStore.value
    };

    const response = await axios.post(
        `/schedule/search/${currentPage.value}/${pageSize.value}`,
        scheduleDTO,  // 请求体传DTO对象
        {
          headers: {
            'Content-Type': 'application/json'
          }
        }
    );

    if (response.data.code === 200) {
      const pageData = response.data.obj;
      tableData.value = transformScheduleData(pageData.records);
      totalData.value = pageData.total;
    } else {
      ElMessage.error('查询失败: ' + response.data.msg);
    }
  } catch (error) {
    console.error('请求排班数据出错:', error);
    ElMessage.error('请求失败: ' + error.message);
  }
};

// 分页变化处理
const handlePageChange = (page) => {
  currentPage.value = page;
  getScheduleData();
};

// 初始化
onMounted(() => {
  getStores();
  getScheduleData();
});
</script>

<style scoped>
.schedule-container {
  padding: 20px;
}

.filter-section {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.filter-item {
  display: flex;
  align-items: center;
  margin-right: 20px;
}

.action-section {
  margin-bottom: 20px;
}

.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>